package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.wx.WechatUtils;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.wechat.domain.vo.WxAuthRes;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.system.service.ISysConfigService;

import java.util.ArrayList;
import java.util.List;

/**
 * 注册验证
 *
 * @author ruoyi
 */
@Slf4j
@RestController
public class SysRegisterController extends BaseController {
    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody user) {
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            return error("当前系统没有开启注册功能！");
        }
        String msg = registerService.register(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }

    /**
     * 功能描述:    小程序：获取openID、session_key
     *
     * @Author wanghc
     * @Date 2022/08/20 17:47
     * @param jsCode
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    @GetMapping("/getOpenid")
    @ApiOperation("小程序：获取openID、session_key")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jsCode", value = "临时登录凭证js_code", paramType = "query", type = "String", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "操作失败!"),
            @ApiResponse(code = 1, message = "操作成功!"),
            @ApiResponse(code = 500, message = "服务器错误"),
    })
    public AjaxResult getOpenid(String jsCode) {
        WxAuthRes wxAuthRes = WxAuthRes.builder().build();
        try {
            String code = !StringUtils.isEmpty(jsCode) ? jsCode : "";
            if(StringUtils.isEmpty(jsCode)){
                return AjaxResult.error("参数为空，请确认");
            }
            // 获取openid 通过自定义工具类组合出小程序需要的登录凭证 code
            String requestUrl = WechatUtils.getMiniprogramLoginUrl(code);
            log.info("》》》获取小程序openid接口为：" + requestUrl);
            JSONObject sessionData = HttpUtils.httpsRequest(requestUrl, "GET", null);
            log.info("》》》获取小程序openid接口返回结果：" + sessionData);
            if (null == sessionData) {
                return AjaxResult.error();
            }
            if(null != sessionData && StringUtils.isEmpty(sessionData.getString("openid"))){
                if(sessionData.getInteger("errcode") != null && sessionData.getInteger("errcode") != 0){
                    return AjaxResult.error();
                }
            }
            wxAuthRes.setOpenid(sessionData.getString("openid"));
            wxAuthRes.setSessionKey(sessionData.getString("session_key"));
        } catch (ServiceException e) {
            return AjaxResult.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取失败");
        }
        return AjaxResult.success(wxAuthRes);
    }

    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/dict/type/{dictType}")
    public AjaxResult dictType(@PathVariable String dictType) {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data)) {
            data = new ArrayList<SysDictData>();
        }
        return AjaxResult.success(data);
    }
}
